package com.zyc.app.woa.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.view.*;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import com.umeng.update.UmengUpdateAgent;
import com.zyc.app.woa.R;
import com.zyc.app.woa.SubscribeAccounts;
import com.zyc.app.woa.data.AccountInfo;
import com.zyc.app.woa.data.CachedArticle;
import com.zyc.app.woa.db.ArticlesTable;
import com.zyc.app.woa.db.DBManager;
import com.zyc.app.woa.db.DBManager.DBObserver;
import com.zyc.app.woa.dialog.AccountDetailDialog;
import com.zyc.app.woa.dialog.DeleteAccountDialog;
import com.zyc.app.woa.fragment.ArticleListFragment;
import com.zyc.app.woa.fragment.BaseFragment;
import com.zyc.app.woa.utils.FragmentUtil;
import com.zyc.app.woa.utils.StatisticUtil;

public class MyActivity extends BaseActivity implements OnItemClickListener {
    private ListView mAccountList;
    private DrawerLayout mDrawerLayout;
    private AccountAdapter mAccountAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private ArticleListFragment mArticleListFragment;
    private AccountInfo mSelectAccountInfo;

    private static final int MSG_ADD_ARTICLE = 1000;
    private static final int CHANGE_ARTICLES_DELAY = 2000;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mAccountList = (ListView) findViewById(R.id.left_drawer);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mAccountAdapter = new AccountAdapter();
        mAccountList.setAdapter(mAccountAdapter);
        mAccountList.setOnItemClickListener(this);
        mAccountList.setLongClickable(false);
        registerForContextMenu(mAccountList);
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, true, R.drawable.ic_drawer, 0, 0) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged(newState);
            }
        };

        if (null == savedInstanceState) {
            selectItem(0);
        }

        UmengUpdateAgent.update(this);
        registerDbObserver();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAccountAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterDbObserver();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }

    private void selectItem(int position) {
        mSelectAccountInfo = SubscribeAccounts.getAccount(position);
        if (null == mArticleListFragment) {
            mArticleListFragment = ArticleListFragment.buildInstance(mSelectAccountInfo);
            launchFragmentNoHistory(mArticleListFragment);
        } else {
            mArticleListFragment.updateContent(mSelectAccountInfo);
        }
        mDrawerLayout.closeDrawer(mAccountList);
        if (null != mSelectAccountInfo) {
            StatisticUtil.readAccount(mSelectAccountInfo);
        }
    }

    @Override
    public void launchFragment(int viewId, BaseFragment fragment) {
        mDrawerLayout.closeDrawers();
        FragmentUtil.launchFragment(getSupportFragmentManager(), viewId, true, fragment);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_bar, menu);
//        initShareMenu(menu.findItem(R.id.action_share));
        return true;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        if (mAccountList == v) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.account_context_menu, menu);
            mSelectAccountInfo = SubscribeAccounts.getAccount(((AdapterContextMenuInfo) menuInfo).position);
        }
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        switch (item.getItemId()) {
            case R.id.action_add_count:
                startActivity(new Intent(this, BrowserActivity.class));
                break;
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.action_feedback:
                startActivity(new Intent(this, ConversationActivity.class));
                break;
            case R.id.action_about:
                startActivity(new Intent(this, AboutActivity.class));
                break;
            case R.id.account_delete:
                if (null != mSelectAccountInfo) {
                    DeleteAccountDialog deleteAccountDialog = new DeleteAccountDialog(this, mSelectAccountInfo);
                    deleteAccountDialog.setOnDeleteButtonClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SubscribeAccounts.deleteAccount(mSelectAccountInfo);
                            mAccountAdapter.notifyDataSetChanged();
                        }
                    });
                    deleteAccountDialog.show();
                }
                break;
            case R.id.account_detail:
                if (null != mSelectAccountInfo) {
                    AccountDetailDialog detailDialog = new AccountDetailDialog(this, mSelectAccountInfo);
                    detailDialog.show();
                }
                break;
            default:
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private void registerDbObserver() {
        DBManager.registerDownloadListener(ArticlesTable.NAME, mDBObserver);
    }

    private void unregisterDbObserver() {
        DBManager.registerDownloadListener(ArticlesTable.NAME, mDBObserver);
    }

    private void initShareMenu(MenuItem shareItem) {
        ShareActionProvider provider = (ShareActionProvider) shareItem.getActionProvider();
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/*");
        provider.setShareIntent(intent);
    }

    private String getInputText(EditText searchBox) {
        Editable editable = searchBox.getEditableText();
        return null != editable ? editable.toString() : null;
    }

    private DBObserver mDBObserver = new DBObserver() {

        @Override
        public void onDelete(Object obj) {

        }

        @Override
        public void onAdd(Object obj) {
            Message message = mHandler.obtainMessage(MSG_ADD_ARTICLE, obj);
            mHandler.sendMessageDelayed(message, CHANGE_ARTICLES_DELAY);
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ADD_ARTICLE:
                    CachedArticle article = (CachedArticle) msg.obj;
                    if (null != mSelectAccountInfo && mSelectAccountInfo.wxId.equals(article.wxId)) {
                        mArticleListFragment.updateContent(mSelectAccountInfo);
                    }
                    mAccountAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    private OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText editText = (EditText) v;
            String hint;
            if (hasFocus) {
                hint = editText.getHint().toString();
                editText.setTag(hint);
                editText.setHint("");
            } else {
                hint = editText.getTag().toString();
                editText.setHint(hint);
            }
        }
    };

    class AccountAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return SubscribeAccounts.getCount();
        }

        @Override
        public AccountInfo getItem(int position) {
            return SubscribeAccounts.getAccount(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = newView(parent);
                convertView.setTag(new ViewHolder(convertView));
            }

            bindView(position, convertView);
            return convertView;
        }

        private View newView(ViewGroup parent) {
            return View.inflate(parent.getContext(), R.layout.drawer_menu_list_item, null);
        }

        private void bindView(int position, View view) {
            ViewHolder holder = (ViewHolder) view.getTag();
            AccountInfo accountInfo = getItem(position);
            if (null != holder && null != accountInfo) {
                holder.mAccountName.setText(accountInfo.name);
                holder.mAccountNum.setText(String.valueOf(accountInfo.totalArticlesNum));
                view.setTag(R.id.view_bind_data, accountInfo);
            }
        }

        private class ViewHolder {
            private TextView mAccountName;
            private TextView mAccountNum;

            public ViewHolder(View view) {
                mAccountName = (TextView) view.findViewById(R.id.title);
                mAccountNum = (TextView) view.findViewById(R.id.counter);
            }
        }
    }

}
